const qiniu = require("qiniu");
const fs = require('fs')
// 创建上传凭证
const accessKey = 'DMhuQkD9zgkzsJE8mGUSlaFqkxbffkeLexabwiZA'    //七牛的accessKey
const secretKey = 'OwFialX0R_r2PPlE4S1b6FVN8aqsj9MqKmQeRxBS'    //七牛的secretKey
const mac = new qiniu.auth.digest.Mac(accessKey, secretKey)
const options = {
    scope: 'tangniaobing-sea',
    expires: 36000, //过期时间为10小时
    returnBody: `{"key":"$(key)","size":$(fsize),"name":"$(fname)","type":"$(mimeType)"}`
}

const keyInQiniuCloud = 'image/' //七牛云文件目录
//服务器直传
const config = new qiniu.conf.Config();
// 华东	qiniu.zone.Zone_z0
// 华北	qiniu.zone.Zone_z1
// 华南	qiniu.zone.Zone_z2
// 北美	qiniu.zone.Zone_na0
// 东南亚	qiniu.zone.Zone_as0
config.zone = qiniu.zone.Zone_as0;//区域
// 是否使用https域名
//config.useHttpsDomain = true;
// 上传是否使用cdn加速
//config.useCdnDomain = true;

//图片的地址
var bucketManager = new qiniu.rs.BucketManager(mac, config);
var privateBucketDomain = 'http://img.zshawk.top'; //七牛中自己配置的域名地址
var deadline = parseInt(Date.now() / 1000) + 3600000; // 永不过期

const getFileUrl = (key) => {
    return bucketManager.privateDownloadUrl(privateBucketDomain, key); //公开空间
    // return bucketManager.privateDownloadUrl(privateBucketDomain, key, deadline); //私有空间
}

// 上传函数
function uploadQiniu(fileObj) {
    // console.log(1111111111111,fileObj.originalname)
    //每次请求都生成一个token
    const putPolicy = new qiniu.rs.PutPolicy(options)
    const uploadToken = putPolicy.uploadToken(mac)
    
    var formUploader = new qiniu.form_up.FormUploader(config);
    var putExtra = new qiniu.form_up.PutExtra();
    // 七牛云上的保存位置、本地服务文件的路径
    return new Promise((resovle, reject) => {
        formUploader.putFile(uploadToken, keyInQiniuCloud + fileObj.originalname, fileObj.path, putExtra, function (respErr, respBody, respInfo) {

            // console.log(222222222222222,respBody)
            if (respErr) throw respErr;
            respBody.url = privateBucketDomain + keyInQiniuCloud + fileObj.originalname
            respBody.name = fileObj.originalname
            fs.unlinkSync(fileObj.path) //删除服务本地文件
            if (respInfo.statusCode == 200) {
                resovle({ code: 200, respBody, message: '七牛上传成功' })
            } else {
                reject({ code: 500,respInfo,message: '七牛上传失败' })
            }
        }
        );
    })
}


module.exports = { uploadQiniu, getFileUrl }